using System;
using System.Web;
using System.Web.UI;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Net;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Specialized;

[WebService(Namespace = "http://yourWebServer/Path/ToThisWebService")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class GSAFeedService : System.Web.Services.WebService
{
    public const string gsaFeedURL = "http://yourGSA.domain.com:19900/xmlfeed";
    public byte[] bytes;
  
    public GSAFeedService()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod(Description = "Service to push XML feeds into the GSA")]
    public bool GSAFeed(string sourceURL, string feedtype, string datasource)
    {
        ASCIIEncoding encoding = new ASCIIEncoding();
        UploadSpec uploadSpecs = new UploadSpec();
        StringDictionary dictionary = new StringDictionary();

        try
        {
            // create new uri to gsa feeder gate
            Uri gsaURI = new Uri(gsaFeedURL);

            // create new uri to the source xml document to feed
            Uri sourceURI = new Uri(sourceURL);

            // get a status code from the source xml document web request 
            // if 200 then web request has access to the xml document
            if ((int)HttpDownload.Download(sourceURI).StatusCode == 200)
            {
                // read response stream
                Stream stream = HttpDownload.Download(sourceURI).GetResponseStream();

                // create streamreader object to read the stream
                StreamReader reader = new StreamReader(stream, System.Text.Encoding.ASCII, false);

                // the the streamed xml document intoa  byte array
                bytes = encoding.GetBytes(reader.ReadToEnd());

                // add feedtype and datasource to dictionary
                dictionary.Add("feedtype", feedtype);
                dictionary.Add("datasource", datasource);

                // add data to upload specs
                uploadSpecs.Contents = bytes;
                uploadSpecs.FileName = sourceURL.Substring(sourceURL.LastIndexOf('/'));
                uploadSpecs.FieldName = "data";

                // upload file and if StatusCode is 200 then post was successful to the gsa
                if ((int)HttpUpload.Upload(gsaURI, dictionary, uploadSpecs).StatusCode == 200)
                {
                    return true;
                }
                else
                {
                    // gsa post not successful
                    return false;
                }
            }
            // no access to xml document
            return false;
        }
        catch (Exception ex)
        {
            throw ex;

        }
    }
}
